package com.tanhua.server.service;

import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @DubboReference
    UserInfoApi userInfoApi;

    @Autowired
    OssTemplate ossTemplate;

    public void save(UserInfo userInfo) {
        UserInfo byId = userInfoApi.findById(userInfo.getId());
        if (byId != null) {
            userInfoApi.update(userInfo);
        } else {
            userInfoApi.save(userInfo);
        }
    }

    public String updateHead(MultipartFile headPhoto, Long id) throws IOException {
        try{

            String headUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(headUrl);
            userInfoApi.update(userInfo);
            return headUrl;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public UserInfo getUserById(Long id) {
        return userInfoApi.findById(id);
    }
}
